import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, render_template, g
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate, MigrateCommand
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf
from redis import StrictRedis

from config import config

db = SQLAlchemy()
redis_store = None

from info.utils.common import do_index_class, user_login_data


def create_login(config_name):
    # 设置日志的记录等级
    logging.basicConfig(level=config[config_name].LOGIN_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    global redis_store
    global migrate
    app = Flask(__name__)

    create_login(config_name)

    app.config.from_object(config[config_name])
    # 开启flakCSRF验证
    CSRFProtect(app)
    # 创建sql对象
    db.init_app(app)
    # 创建对象
    redis_store = StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT)

    @app.after_request
    def after_request(response):
        # 调用函数生成 csrf_token
        csrf_token = generate_csrf()
        # 通过cookie将值传给前端
        response.set_cookie("csrf_token", csrf_token)
        return response

    # 注册过滤器
    app.add_template_filter(do_index_class, "index_class")

    # 注册蓝图

    from info.modules.index import index_blue
    from info.modules.passport import passport_blue
    from info.modules.news import news_blue
    from info.modules.user import user_blue
    from info.modules.profile import profile_blue
    app.register_blueprint(index_blue)
    app.register_blueprint(passport_blue)
    app.register_blueprint(news_blue)
    app.register_blueprint(user_blue)
    app.register_blueprint(profile_blue)

    @app.errorhandler(404)
    @user_login_data
    def error(_):
        # 实例化用户对象
        user = g.user
        data = {
            "user_info": user.to_dict() if user else None,
        }
        return render_template("news/404.html", data=data)

    # 使用manage管理app
    manager = Manager(app)
    # 生成迁移
    migrate = Migrate(app, db)
    manager.add_command('db', MigrateCommand)

    return manager
